/*
 * Created by Gibbs on 2021/1/1.
 * Copyright (c) 2021 Gibbs. All rights reserved.
 */

#include "LoopThreadHelper.h"

#include <utility>

LoopThread *
LoopThreadHelper::createLoopThread(const std::string &name,
                                   const std::function<int(int, long)> &updateFunc) {
    return LoopThreadHelper::createLoopThread(name, nullptr, updateFunc, nullptr);
}

LoopThread *LoopThreadHelper::createLoopThread(const std::string &name,
                                               const std::function<int(int, long)> &updateFunc,
                                               const std::function<void(int, std::string)> &notifyFunc) {
    return LoopThreadHelper::createLoopThread(name, nullptr, updateFunc, nullptr, notifyFunc);
}

LoopThread *LoopThreadHelper::createLoopThread(const std::string &name,
                                               const std::function<void(void)> &startFunc,
                                               const std::function<int(int, long)> &updateFunc,
                                               const std::function<void()> &endFunc) {
    return LoopThreadHelper::createLoopThread(name, startFunc, updateFunc, endFunc, nullptr);
}

LoopThread *LoopThreadHelper::createLoopThread(const std::string &name,
                                               const std::function<void(void)> &startFunc,
                                               const std::function<int(int, long)> &updateFunc,
                                               const std::function<void()> &endFunc,
                                               const function<void(int, std::string)> &notifyFunc) {
    auto *thread = new LoopThread(name);
    if (startFunc != nullptr) {
        thread->setStartFunc(startFunc);
    }
    if (updateFunc != nullptr) {
        thread->setUpdateFunc(updateFunc);
    }
    if (endFunc != nullptr) {
        thread->setEndFunc(endFunc);
    }
    if (notifyFunc != nullptr) {
        thread->setNotifyFunc(notifyFunc);
    }
    thread->start();
    return thread;
}

void LoopThreadHelper::stopLoopThread(LoopThread *thread) {
    if (thread && thread->hasStarted()) {
        thread->stop();
        thread->join();
        delete thread;
    }
}
